<?php
namespace app\controller;

use support\Request;
use Qiniu\Auth as Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

/**
 * 文件上传类
 */
class Upload extends Base
{
	public $picUrl = 'http://webman.tinphp.com';
    protected $qiniuConfig = [
        'qn_ak' => 'bpM4mYnptD8-CJU4pinhcalz3UTlduMdD55PiN8i',
        'qn_sk' => 'IZ9YSqdtlfxC3UuPi9kXSQXu9URpehSrFBBqDtZG',
        'qn_bucket' => 'szg-file',
        'qn_domain' => 'http://qiniuyunfile.yinsheng.top',
    ];

    /**
     * 单文件上传
     * 上传至本地服务器
     */
    public function upFile(Request $request)
    {
        $file = $request->file('file');
        if ($file && $file->isValid()) {
            //验证上传文件类型
            $allowName = $file->getUploadExtension();       //获取文件后缀
            if ($this->allow($allowName) == false) {
                return return_json(0, '不允许该文件类型上传');
            }

            $fileRootPath = public_path();
            $filePathTemp = "/uploads/" . date("Y") . "/" . date("m") . "/";
            $fileName = time() . $this->GetRandStr(5) . '.' . $allowName;

            $file->move($fileRootPath . $filePathTemp . $fileName);

            $picUrl = $this->picUrl;
            $picUrl = rtrim($picUrl,'/');
            $data = [
                'picurl' => $picUrl . $filePathTemp . $fileName
            ];

            return return_json(1, '文件上传成功', $data);

        }
        return return_json(0, '文件上传失败');
    }
	
	/**
     * 批量上传
     * 上传至本地服务器
     */
    public function upFileAll(Request $request)
    {
		$url = [];
        $i = 0;
		foreach ($request->file() as $key => $spl_file) {
            $file = $spl_file[$i];
			if ($file->isValid()) {
				//获取文件的后缀名称
				$allowName = $file->getUploadExtension();
				//获得文件大小
				$size = $file->getSize();

				$error = 0;
				$maxSize = config('server.max_package_size');
				
				//判断文件类型是否允许上传
				if ($this->allow($allowName) == false) {
					$error = '该文件类型禁止上传';
				}

				//判断文件大小是否超出
				if ($size > $maxSize){
					$error = '该文件太大禁止上传';
				}
				
				$fileRootPath = public_path();										//根目录
				$filePathTemp = "/uploads/" . date("Y") . "/" . date("m") . "/";	//上传文件目录
				$fileName = time() . $this->GetRandStr(5) . '.' . $allowName;		//重命名文件

				//获取文件的完整url地址
				$picUrl = $this->picUrl;
				$picUrl = rtrim($picUrl,'/');
				$url[$i]['url'] = $picUrl . $filePathTemp . $fileName;
				$url[$i]['name'] = $file->getUploadName();
				$url[$i]['error'] = $error;
				if(!$error){
					//将上传的文件移动到指定目录
					$file->move($fileRootPath . $filePathTemp . $fileName);
				}
                $i++;
			}
		}
        
        return json($url);
    }

    //随机创建文件名
    //GetRandStr(10);
    public function GetRandStr($len)
    {
        $chars = array(
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        $charsLen = count($chars) - 1;
        shuffle($chars);
        $output = '';
        for ($i = 0; $i < $len; $i++) {
            $output .= $chars[mt_rand(0, $charsLen)];
        }
        return $output;
    }

    //验证文件后缀名
    public function allow($allowName)
    {
        $allowarray = array('png', 'jpg', 'jpeg', 'bmp', 'gif', 'pic', 'tif', 'doc', 'docx', 'pdf', 'tif', 'xml', 'dotm', 'docm', 'dotx', 'dot', 'xlsx', 'xlsm', 'xltx', 'xltm', 'xlsb', 'xlam', 'pptx', 'pptm', 'ppsx', 'potx', 'potm', 'ppam', 'xls', 'gz', 'mp4', 'mp3', 'html');
        if (in_array($allowName, $allowarray)) {
            return true;
        }else{
            return false;
        }
    }

    /**
     * qiniu 单文件上传
     */
    public function qiniuFile(Request $request)
    {
        $file = $request->file('file');
        if ($file && $file->isValid()) {
            //验证上传文件类型
            $allowName = $file->getUploadExtension();       //获取文件后缀
            if ($this->allow($allowName) == false) {
                return ajaxReturn(0, '不允许该文件类型上传');
            }

            //获取上传配置
            $infoConfig = $this->qiniuConfig;

            //要上传图片的本地路径
            $filePath = $file->getRealPath();

            //上传到七牛后保存的文件名
            $key = $this->GetRandStr(5) . date('YmdHis') . rand(10000, 99999) . '.' . $allowName;

            //需要填写你的 Access Key 和 Secret Key
            $accessKey = $infoConfig['qn_ak'];
            $secretKey = $infoConfig['qn_sk'];
            //需要填写你的 要上传的空间
            $bucket = $infoConfig['qn_bucket'];
            //需要填写你的 绑定域名
            $domain = $infoConfig['qn_domain'];

            //构建鉴权对象
            $auth = new Auth($accessKey, $secretKey);
            $token = $auth->uploadToken($bucket);

            //初始化 UploadManager 对象并进行文件的上传
            $uploadMgr = new UploadManager();
            //调用 UploadManager 的 putFile 方法进行文件的上传
            list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
            if ($err !== null) {
                return ajaxReturn(0, '上传失败', '', $err);
            } else {
                //返回图片的完整URL
                $url = $domain . '/' . $ret['key'];
                $data = [
                    'picurl' => $url,
                ];

                return return_json(1, '上传成功', $data);
            }
        }
        return return_json(0, '文件上传失败');
    }


}
